﻿using System;
using Skyper.View;
using System.Collections.Generic;
using Skyper.View.Chat;
using Skyper.Model;
using System.Windows.Controls;
using System.Windows;
namespace Skyper.Presenters {
	public class ChatPagePresenter : Presenter<IChatPageView> {
		#region Fields
		private readonly List<ChatItemPresenter> presenters = new List<ChatItemPresenter>();
		#endregion
		#region Constructor
		public ChatPagePresenter(IChatPageView view)
			: base(view) {


			this.View.SelectedChatChanged += new RoutedEventHandler(View_SelectedChatChanged);
		}
		#endregion
		#region Private
		private void View_SelectedChatChanged(object sender, RoutedEventArgs e) {

		}
		#endregion
		#region Public
		public sealed override void Refresh() {
			this.presenters.Clear();
			List<IChatItemView> views = new List<IChatItemView>();



			var page = this.View as Page;
			String username = null;
			if (page != null && page.NavigationContext != null) {
				username = page.NavigationContext.QueryString["Username"];
			}
			IChatItemView active = null;
			if (App.Skype.Chats != null) {
				foreach (var chat in App.Skype.Chats) {
					IChatItemView view = new ChatItemView();
					ChatItemPresenter prt = new ChatItemPresenter(view, chat);

					if (chat.Contact.Username == username) {
						active = view;
					}

					views.Add(view);

					this.presenters.Add(prt);
				}
			}
			if (!String.IsNullOrEmpty(username) && active == null) {
				var chat = App.Skype.GetChat(username);
				if (chat != null) {
					var view = new ChatItemView();
					var prt = new ChatItemPresenter(view, chat);
					active = view;
					views.Add(view);

					this.presenters.Add(prt);
				}
			}
			this.View.Chats = views;
			this.View.ActiveChat = active;


		}
		#endregion
	}
}
